<div id="html-template" class="hide">
    <li class="commodity-comment">
        <div class="comment-avatar-block"><img class="avatar" src="" alt="用户头像" style="max-width:100%; max-height:100%"/></div>
        <div class="comment-main-block">
            <div class="username">#username#</div>
            <div class="time">#time#</div>
            <div><span class="private"></span><span class="father-comment-username"></span><span class="comment-content">#content#</span></div>
            <a href="javascript:" class="leave-comment-reply-btn">回复</a>
        </div>
        <form class="leave-commodity-comment" method="post" style="display: none">
            <div class="form-content" style="overflow: hidden">
                <input type="hidden" name="commodity_id">
                <input type="hidden" name="father_id">

                <div class="input-group">
                    <label class="input-group-addon sr-only">回复</label>
                    <textarea name="content" class="form-control reply-textarea" placeholder="请输入回复内容" required="required"></textarea>
                </div>
                <div class="pull-right">
                    <input type="checkbox" name="private" style="vertical-align:-2px"/>
                    <span class="secret-txt">密谈</span>
                    <input type="submit" class="btn btn-primary" value="发表"/>
                </div>
            </div>
        </form>
        <ul class="sub-comment-block"></ul>
    </li>
</div>

<div id="main">
    <div id="home-body">
        <?php if (isset($thatCommodity)): ?>
            <?php /** @var Commodity $thatCommodity */ ?>
            <div id="commodity-<?php echo $thatCommodity->getId() ?>" class="commodity">
                <div id="details">
                    <div class="metro-style">
                        <div class="title">
                            <span><?php echo $thatCommodity->getTitle() ?></span>
                        </div>
                        <div class="plus-one">
                            <?php if (isset($CurrentUser) && $CurrentUser->getId() > 0 && $thatCommodity->isCommodityPlusOneExistWithUserId($CurrentUser->getId())): ?>
                                <a href="javascript:" class="commodity-toggle-plus-one" data-commodity-id="<?php echo $thatCommodity->getId() ?>"><span class="glyphicon glyphicon-thumbs-up"></span>已赞(<?php echo $thatCommodity->getPlusOneCount() ?>)</a>
                            <?php else : ?>
                                <a href="javascript:" class="commodity-toggle-plus-one" data-commodity-id="<?php echo $thatCommodity->getId() ?>"><span class="glyphicon glyphicon-thumbs-up"></span>赞(<?php echo $thatCommodity->getPlusOneCount() ?>)</a>
                            <?php endif; ?>
                        </div>
                        <div class="favorite">
                            <?php if (isset($CurrentUser) && $CurrentUser->getId() > 0 && $thatCommodity->isCommodityFavoriteExistWithUserId($CurrentUser->getId())): ?>
                                <a href="javascript:" class="commodity-toggle-favorite" data-commodity-id="<?php echo $thatCommodity->getId() ?>"><span class="glyphicon glyphicon-heart"></span>已收藏</a>
                            <?php else : ?>
                                <a href="javascript:" class="commodity-toggle-favorite" data-commodity-id="<?php echo $thatCommodity->getId() ?>"><span class="glyphicon glyphicon-heart"></span>收藏</a>
                            <?php endif; ?>
                        </div>
                        <div class="release-type">
                            <img src="<?php echo base_url('public/images/icon/details/state.png') ?>" alt="发布类型"/>
                            <span><?php echo $thatCommodity->getDisplayReleaseType() ?></span>
                        </div>
                        <div class="detail-price">
                            <img src="<?php echo base_url('public/images/icon/details/price.png') ?>" alt="价格"/>
                            <span><?php echo $thatCommodity->getDisplayPrice() ?></span>
                        </div>
                        <div class="stock">
                            <img src="<?php echo base_url('public/images/icon/details/lz.png') ?>" alt="库存"/>
                            <span><?php echo $thatCommodity->getDisplayStock() ?></span>
                        </div>
                        <div class="c-u-t-block">
                            <?php echo($thatCommodity->getContactType()==3)?'<a href="http://wpa.qq.com/msgrd?v=3&uin='.$thatCommodity->getDisplayContactInfo().'&site=qq&menu=yes" >':'';?>
                            <div class="contact">
                                <img src="<?php echo ($thatCommodity->getContactType()==3)?base_url('public/images/icon/details/qq.png'):base_url('public/images/icon/details/phone.png'); ?>" alt="联系方式"/>
                                <?php if (isset($CurrentUser) && $CurrentUser->getId() !== 0): ?>
                                    <span><?php echo $thatCommodity->getDisplayContactInfo() ?></span>
                                <?php else: ?>
                                    <span><a class="gotologin" href="javascript:" style="background: #60bdaf; text-decoration: underline; font-size: 14px;">登录后查看</a></span>
                                <?php endif;?>
                            </div>
                            <?php echo($thatCommodity->getContactType()==3)?'<a/>':'';?>
                            <div class="user-name">
                                <img src="<?php echo ($thatCommodity->getUserSex())?(($thatCommodity->getUserSex()==2)?base_url('public/images/icon/details/girl.png'):base_url('public/images/icon/details/boy.png')):base_url('public/images/icon/details/boy.png'); ?>" alt="联系人"/>
                                <?php if (isset($CurrentUser) && $CurrentUser->getId() !== 0 && $thatCommodity->getUserTrueName()): ?>
                                    <span><?php echo  mb_substr($thatCommodity->getUserTrueName(),0,1,"UTF-8");?>同学</span>
                                <?php else: ?>
                                    <span><a class="gotologin" href="javascript:" style="background: #60bdaf; text-decoration: underline; font-size: 14px;">登录后查看</a></span>
                                <?php endif;?>
                            </div>
                            <div class="release-time">
                                <span><?php echo $thatCommodity->getReleaseTime() ?></span>
                            </div>
                        </div>
                        <div class="share_qq">
                            <a href="javascript:"><img src="<?php echo base_url('public/images/icon/details/share-qq.png') ?>" alt="分享到QQ空间" style="margin-top:18px; margin-left:16px;"/></a>
                        </div>
                        <div class="share_weibo">
                            <a href="javascript:"><img src="<?php echo base_url('public/images/icon/details/weibo.png') ?>" alt="分享到微博" style="margin-top:18px; margin-left:13px;"/></a>
                        </div>
                        <div class="share_weixin">
                            <a href="javascript:"><img src="<?php echo base_url('public/images/icon/details/weixin.png') ?>" alt="分享到微信" style="margin-top:18px; margin-left:9px;"/></a>
                        </div>
                    </div>
                    <div class="commodity-details-tab-block">
                        <ul class="nav nav-tabs">
                            <li class="active"><a href="#commodity-content" data-toggle="tab">商品描述</a></li>
                            <li><a href="#commodity-comment" data-toggle="tab" class="show-comment" data-commodity-id="<?php echo $thatCommodity->getId() ?>">留言</a></li>
                        </ul>

                        <div class="tab-content">
                            <div class="tab-pane fade in active" id="commodity-content">
                                <?php echo YimeTools::sanitize_html($thatCommodity->getContent()); ?>
                                <p style="color: #ba1d27;">(联系我的时候，请说明在易米网上看见的哦，吼吼(╯▽╰)！)</p>
                            </div>
                            <div class="tab-pane fade" id="commodity-comment">
                                <div class="leave-comment">
                                    <?php if (isset($CurrentUser) && $CurrentUser->getId() !== 0): ?>
                                        <form class="leave-commodity-comment" method="post" data-master-comment-id="0">
                                            <div class="form-content" style="overflow: hidden">
                                                <input type="hidden" name="commodity_id" value="<?php echo $thatCommodity->getId() ?>">
                                                <input type="hidden" name="father_id" value="0">

                                                <div class="input-group">
                                                    <label class="input-group-addon sr-only">回复</label>
                                                    <textarea name="content" class="form-control reply-textarea" placeholder="请输入回复内容" required="required"></textarea>
                                                </div>
                                                <div class="pull-right">
                                                    <input type="checkbox" name="private" style="vertical-align:-2px"/>
                                                    <span class="secret-txt">密谈</span>
                                                    <input type="submit" class="btn btn-primary" value="发表"/>
                                                </div>
                                            </div>
                                        </form>
                                    <?php else: ?>
                                        <div class="comment-user-nologin">
                                            要留言？请先&nbsp;&nbsp;<a class="signIn" href="javascript:">登录</a>&nbsp;&nbsp;或&nbsp;&nbsp;<a class="signUp" href="javascript:">注册</a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <ul class="list-comment list-unstyled"></ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div id="home-sidebar">
        <?php $this->load->view('home/home-sidebar'); ?>
    </div>
</div>

<script type="text/javascript">
function appendCommodityComment($block, comment, fatherUsername, masterCommentId) {
    var $comment = $('#html-template').find('.commodity-comment').clone().addClass('hide').appendTo($block);
    $comment.attr('id', 'commodity-comment-' + comment.id);
    $comment.attr('data-comment-id', comment.id);
    $comment.find('.avatar').attr('src', comment.userAvatarUrl);
    $comment.find('.username').html(comment.userDisplayName);
    $comment.find('.time').html(comment.releaseTime);
    $comment.find('.comment-content').html(comment.content);
    $comment.find('form.leave-commodity-comment-reply').attr('data-ajax-append-id', masterCommentId);
    var $leaveCommentForm = $comment.find('.leave-commodity-comment');
    $leaveCommentForm.attr('data-father-name', comment.userDisplayName);
    $leaveCommentForm.attr('data-master-comment-id', comment.id);
    $leaveCommentForm.find('input[name=commodity_id]').val(comment.commodityId);
    $leaveCommentForm.find('input[name=father_id]').val(comment.id);
    if (comment.private == true)
        $comment.find('.private').html('[密谈]');
    if (fatherUsername)
        $comment.find('.father-comment-username').html('@' + fatherUsername);
    $comment.removeClass('hide');
    return $comment;
}

function appendCommodityCommentByCommentSet(commentSet) {
    var commodityId = commentSet.commodityId;
    var $commentList = $('#commodity-' + commodityId).find('.list-comment');
    commentSet.masterCommentIdArraySortByReleaseTime.forEach(function (commentId) {
        var comment = commentSet.comments[commentId];
        if (comment) {
            var $comment = appendCommodityComment($commentList, comment, undefined, comment.id);
            var $subCommentBlock = $comment.find('.sub-comment-block');
            comment.descendantCommentIdArraySortByReleaseTime.forEach(function (subCommentId) {
                var subComment = commentSet.comments[subCommentId];
                appendCommodityComment($subCommentBlock, subComment, commentSet.comments[subComment.fatherId] ? commentSet.comments[subComment.fatherId].userDisplayName : undefined, comment.id);
            });
        }
    });
}

function appendCommodityCommentByCommodityId(commodity_id) {
    CommodityCommentSet.InitByCommodityId(commodity_id, appendCommodityCommentByCommentSet);
}

$(document).on('submit', 'form.leave-commodity-comment', function (event) {
    event.preventDefault();
    var form = this;
    var fatherName = $(form).data('father-name');
    var masterCommentId = $(form).data('master-comment-id');
    $.ajax({
        url: base_url('api/leaveCommodityComment'),
        type: 'post',
        data: $(form).serialize(),
        success: function (jsonrsp) {
            try {
                var rsp = $.parseJSON(jsonrsp);
                switch (rsp.type) {
                    case 'success':
                        noty({type: rsp.type, text: rsp.message});
                        var $commentCount = $(form).closest('.commodity').find('.comment-count');
                        var commentCount = $commentCount.text();
                        $commentCount.text(+commentCount + +1);
                        $(form).find('[name=content]').val('');
                        var comment = CommodityComment.InitByJsonData(rsp.data);
                        if (masterCommentId != 0) {
                            $(form).slideUp();
                            appendCommodityComment($('#commodity-comment-' + masterCommentId).children('.sub-comment-block'), comment, fatherName, masterCommentId);
                        }
                        else
                            appendCommodityComment($('#commodity-' + comment.commodityId).find('.list-comment'), comment, fatherName, masterCommentId);
                        break;
                    default:
                        noty({type: rsp.type, text: rsp.message});
                        break;
                }
            } catch (ex) {
                noty({type: 'error', text: '发生内部错误，请联系管理员'});
                throw ex;
            }
        }
    });
});

$(document).on('click', '.show-comment', function () {
    var commodityId = $(this).data('commodity-id');
    var $thisCommodity = $('#commodity-' + commodityId);
    var $commentList = $thisCommodity.find('.list-comment');
    $commentList.empty();
    appendCommodityCommentByCommodityId(commodityId);
});

$(document).on('click', '.leave-comment-reply-btn', function () {
    var commodityId = $(this).closest('.commodity').data('commodity-id');
    var commentId = $(this).closest('.commodity-comment').data('comment-id');
    var $comment = $(this).closest('li#commodity-comment-' + commentId);
    var $leaveComment = $comment.children('.leave-commodity-comment');
    if ($leaveComment.css('display') == 'none') {
        $leaveComment.slideDown();
    } else {
        $leaveComment.slideUp();
    }
});


$(document).on('click', '.commodity-toggle-plus-one', function () {
    var _this = this;
    var commodityId = $(this).data('commodity-id');
    $.ajax({
        url: '<?php echo base_url('api/commodityTogglePlusOne');?>',
        type: 'get',
        data: {commodity_id: commodityId},
        beforeSend: function () {
        },
        complete: function () {
        },
        success: function (jsonrsp) {
            try {
                var rsp = $.parseJSON(jsonrsp);
                switch (rsp.type) {
                    case 'success':
                        if (rsp.data.isCommodityPlusOneNow) {
                            $(_this).html('<span class=" glyphicon glyphicon-thumbs-up"></span>已赞(' + rsp.data.countCommodityPlusOneNow + ')');
                        } else {
                            $(_this).html('<span class=" glyphicon glyphicon-thumbs-up"></span>赞(' + rsp.data.countCommodityPlusOneNow + ')');
                        }
                        break;
                    case 'error':
                        if (rsp.message == 'NOTLOGIN') {
                            showDialog('login');
                        }
                        break;
                    default:
                        break;
                }
            } catch (e) {
                console.error(e);
                noty({type: 'error', text: '发生内部错误，请联系管理员'});
            }
        }
    });
});

$(document).on('click', '.commodity-toggle-favorite', function () {
    var _this = this;
    var commodityId = $(this).data('commodity-id');
    $.ajax({
        url: '<?php echo base_url('api/commodityToggleFavorite');?>',
        type: 'get',
        data: {commodity_id: commodityId},
        beforeSend: function () {
        },
        complete: function () {
        },
        success: function (jsonrsp) {
            try {
                var rsp = $.parseJSON(jsonrsp);
                switch (rsp.type) {
                    case 'success':
                        if (rsp.data.isCommodityInFavoriteNow) {
                            $(_this).html('<span class="glyphicon glyphicon-heart"></span>已收藏');
                        } else {
                            $(_this).html('<span class="glyphicon glyphicon-heart"></span>收藏');
                        }
                        break;
                    case 'error':
                        if (rsp.message == 'NOTLOGIN') {
                            showDialog('login');
                        }
                        break;
                    default:
                        break;
                }
            } catch (e) {
                console.error(e);
                noty({type: 'error', text: '发生内部错误，请联系管理员'});
            }
        }
    });
});
</script>